package com.zyx.msmservice.controller;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import com.zyx.commonutils.R;
import com.zyx.msmservice.service.MsmService;
import com.zyx.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zyx
 * @version 1.0
 * @date 2022/1/8 008 14:33
 */
@RequestMapping("/edumsm/msm")
@RestController
//@CrossOrigin
public class MsmController {

    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {

        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        code = RandomUtil.getSixBitRandom();
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        boolean isSend = msmService.send(map, phone);
        if (isSend) {
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }


    @GetMapping("/sentEmail/{phone}")
    public R sentEmail(@PathVariable String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {return R.ok();}
        code = RandomUtil.getFourBitRandom();
        boolean  flag = msmService.sent(phone, "注册验证码", code);
        if(flag){
            redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败");
        }

    }
}
